package com.budwk.app.sqfwV2.service.meeting.impl;

import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.config.AppException;
import com.budwk.app.exception.ServiceException;
import com.budwk.app.sqfw.component.CommunityStreetComponent;
import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_formSummary;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwCompleteflowService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.vo.AreaAddressVo;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfw.vo.Sqfw_formSummaryForAdminVO;
import com.budwk.app.sqfwV2.dto.MeetingParamDTO;
import com.budwk.app.sqfwV2.enums.MeetingEnums;
import com.budwk.app.sqfwV2.service.meeting.MeetingExcelService;
import com.budwk.app.sqfwV2.service.meeting.MeetingPdfService;
import com.budwk.app.sqfwV2.service.meeting.MeetingService;
import com.budwk.app.util.AuthorityUtil;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.security.utils.SecurityUtil;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhangp
 * @description TODO
 * @className MeetingServiceImpl
 * @Date 16:39 2024/2/1
 */
@IocBean
public class MeetingServiceImpl implements MeetingService {
    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;

    @Inject
    private MeetingPdfService meetingPdfService;
    @Inject
    private MeetingExcelService meetingExcelService;

    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;


    @Override
    public Pagination listSummaryMeetingByPage(Sqfw_formSummaryForAdminVO forAdminVo) {
        Criteria criteria = buildMeetingQueryCond(forAdminVo);
        // 2 分页查询
        return sqfwFormsummaryNewService.listPage(forAdminVo.getPageNo(), forAdminVo.getPageSize(), criteria);
    }

    @Override
    public List<Sqfw_formSummary_new> listSummaryMeeting(Sqfw_formSummaryForAdminVO forAdminVo) {
        Criteria criteria = buildMeetingQueryCond(forAdminVo);
        return sqfwFormsummaryNewService.query(criteria);
    }

    @Override
    public String generatorFile(Integer templateCode, boolean isTemplate, String sqwfIds) {
        String url = null;
        if (MeetingEnums.DOCX_SUMMARY.getCode() == templateCode) {
            //pdf下载
            url = meetingPdfService.generatePDF(templateCode, isTemplate, SecurityUtil.getUserId(), sqwfIds, false);
        } else {
            //excel下载
            List<GenerateExcelUrlVO> generateExcel = meetingExcelService.generateExcel(templateCode, isTemplate, SecurityUtil.getUserId(), sqwfIds, false);
            if (!generateExcel.isEmpty()) {
                url = generateExcel.get(0).getExcelUrl();
            }
        }

        if (StringUtils.isBlank(url)) {
            throw new ServiceException("暂无数据！");
        }
        return url;
    }

    @Override
    public String generateMeetingExcelCollZipForBM(Sqfw_formSummaryForAdminVO forAdminVo, Integer templateCode, boolean isTemplate, String entry, String ids) {
        String url = null;
        String sqwfIds = null;
        if ("select".equals(entry)) {
            sqwfIds = ids;
        } else {
            //查询导出数据
            forAdminVo.setPageNo(null);
            forAdminVo.setPageSize(null);
            List<Sqfw_formSummary_new> sqfwFormSummaryNewList = listSummaryMeeting(forAdminVo);
            sqwfIds = sqfwFormSummaryNewList.stream().map(Sqfw_formSummary_new::getId).distinct().collect(Collectors.joining(","));
        }
        if (!isTemplate) {
            //选择导出数据
            if (StringUtils.isBlank(sqwfIds)) {
                throw new ServiceException("暂无数据！");
            }
        }
        if (MeetingEnums.DOCX_SUMMARY.getCode() == templateCode) {
            //pdf下载
            url = meetingPdfService.generatePDF(templateCode, isTemplate, SecurityUtil.getUserId(), sqwfIds, true);
        } else {
            //excel下载
            List<GenerateExcelUrlVO> generateExcel = meetingExcelService.generateExcel(templateCode, isTemplate, SecurityUtil.getUserId(), sqwfIds, true);
            if (!generateExcel.isEmpty()) {
                url = generateExcel.get(0).getExcelUrl();
            }
        }
        if (org.apache.commons.lang.StringUtils.isBlank(url)) {
            throw new ServiceException("暂无数据！");
        }
        return url;
    }

    @Override
    public List<Integer> generateMeetingCheckDataForAdmin(Sqfw_formSummaryForAdminVO forAdminVo, String entry, String ids) {
        String sqwfIds = null;
        if ("select".equals(entry)) {
            sqwfIds = ids;
        } else {
            forAdminVo.setPageNo(null);
            forAdminVo.setPageSize(null);
            List<Sqfw_formSummary_new> sqfwFormSummaryNewList = listSummaryMeeting(forAdminVo);
            sqwfIds = sqfwFormSummaryNewList.stream().map(Sqfw_formSummary_new::getId).distinct().collect(Collectors.joining(","));
        }
        if (StringUtils.isBlank(sqwfIds)) {
            return Lists.newArrayList();
        }
        return checkData(sqwfIds, true);
    }

    @Override
    public List<Integer> checkData(String sqfwIds, boolean isAdmin) {
        List<Integer> indexList = org.apache.commons.compress.utils.Lists.newArrayList();
        for (MeetingEnums enumObj : MeetingEnums.values()) {
            if (enumObj.isLoopLable()) {
                if (!indexList.contains(enumObj.getCode())) {
                    Cnd cnd = Cnd.where(Sqfw_formSummary_new::getType, "=", SupportBusinessTypeEnum.MEETING_ACTIVITY_VISIT_RECORD.getCode());
                    if (isAdmin) {
                        cnd.and(Sqfw_formSummary_new::getId, "in", com.google.common.collect.Lists.newArrayList(sqfwIds.split(",")));
                    } else {
                        cnd.and(Sqfw_formSummary_new::getSqfwId, "in", com.google.common.collect.Lists.newArrayList(sqfwIds.split(",")));
                    }
                    cnd.and(" param_data ->>'type'", "=", enumObj.getName().split("_")[0]);
                    int num = sqfwFormsummaryNewService.count(cnd);
                    if (num > 0) {
                        indexList.add(enumObj.getCode());
                        if (MeetingEnums.MEETING_MINUTES_EXCEL.getCode() == enumObj.getCode()) {
                            indexList.add(MeetingEnums.MEETING_MINUTES_DETAIL_EXCEL.getCode());
                        }
                        if (!indexList.contains(MeetingEnums.DOCX_SUMMARY.getCode())) {
                            indexList.add(MeetingEnums.DOCX_SUMMARY.getCode());
                        }
                    }
                }
            }
        }
        return indexList;
    }

    @Override
    public Result<?> queryMeetNameHistory(String type, String theme) {
        if (StringUtils.isEmpty(theme)) {
            throw new AppException("请输入内容！");
        }
        Criteria cri = Cnd.cri();
        SqlExpressionGroup criSql = cri.where();
        Sqfw_formSummaryForAdminVO bean = new Sqfw_formSummaryForAdminVO();
        // 数据权限操作查询条件
        AreaAddressVo areaAddressVo = AuthorityUtil.checkFormSummaryAreaPermission(bean);
        AuthorityUtil.commonPermissionLikeQuery(criSql, areaAddressVo);
        criSql.and("param_data ->> 'type' ", "=", type);
        criSql.andLike("param_data ->> 'theme' ", theme);
        criSql.andEquals(Sqfw_formSummary_new::getType, SupportBusinessTypeEnum.MEETING_ACTIVITY_VISIT_RECORD.getCode());
        cri.getOrderBy().desc(Sqfw_formSummary_new::getFillDate);
        List<Sqfw_formSummary_new> list = sqfwFormsummaryNewService.query(cri);
        List<Sqfw_formSummary_new> sqfwFormSummaryNewList = Lists.newArrayList();
        List<String> themeNameList = Lists.newArrayList();
        for (Sqfw_formSummary_new item : list) {
            MeetingParamDTO meetingParamDTO = JSONObject.parseObject(item.getParamData(), MeetingParamDTO.class);
            if (!themeNameList.contains(meetingParamDTO.getTheme())) {
                sqfwFormSummaryNewList.add(item);
                themeNameList.add(meetingParamDTO.getTheme());
            }
        }
        return Result.data(sqfwFormSummaryNewList);
    }


    /**
     * 后台列表公共查询参数设置
     *
     * @param forAdminVo
     * @return
     */
    public Criteria buildMeetingQueryCond(Sqfw_formSummaryForAdminVO forAdminVo) {
        Criteria cri = Cnd.cri();
        SqlExpressionGroup expressionSql = cri.where();
        AreaAddressVo areaAddressVo = AuthorityUtil.checkFormSummaryAreaPermission(forAdminVo);
        // 公共查询
        AuthorityUtil.commonPermissionLikeQuery(expressionSql, areaAddressVo);
        // 组装查询条件
        if (StringUtils.isNotBlank(forAdminVo.getPageOrderName()) && StringUtils.isNotBlank(forAdminVo.getPageOrderBy())) {
            if (forAdminVo.getPageOrderBy().equals(CommonConstants.ASC)) {
                cri.getOrderBy().asc(forAdminVo.getPageOrderName());
            }
            if (forAdminVo.getPageOrderBy().equals(CommonConstants.DESC)) {
                cri.getOrderBy().desc(forAdminVo.getPageOrderName());
            }
        } else {
            cri.getOrderBy().desc(Sqfw_formSummary::getCreateDate);
        }
        expressionSql.andEquals(Sqfw_formSummary::getType, SupportBusinessTypeEnum.MEETING_ACTIVITY_VISIT_RECORD.getCode());
        // 会议时间
        CommunityStreetComponent.handleFillQueryTime(forAdminVo, expressionSql);
        // 提交时间
        CommunityStreetComponent.handleQueryTime(forAdminVo, expressionSql);
        // 会议主题 theme
        if (StringUtils.isNotBlank(forAdminVo.getTheme())) {
            expressionSql.andLike("param_data ->> 'theme'", forAdminVo.getTheme());
        }
        // 会议地点】取值address
        if (StringUtils.isNotBlank(forAdminVo.getAddress())) {
            expressionSql.andLike("param_data ->> 'address'", forAdminVo.getAddress());
        }
        // 会议地点】取值address
        if (StringUtils.isNotBlank(forAdminVo.getType())) {
            expressionSql.andIn("param_data ->> 'type'", forAdminVo.getType());
        }
        // 提交人
        if (StringUtils.isNotBlank(forAdminVo.getCreateUserName())) {
            expressionSql.andLike(Sqfw_formSummary::getCreateUserName, forAdminVo.getCreateUserName());
        }
        if (StringUtils.isNotBlank(forAdminVo.getQueryAll())) {
            String queryAll = forAdminVo.getQueryAll();
            SqlExpressionGroup type = Cnd.exps("param_data ->> 'type'", "like", "%" + queryAll + "%");
            SqlExpressionGroup address = Cnd.exps("param_data ->> 'address'", "like", "%" + queryAll + "%");
            SqlExpressionGroup meetingContent = Cnd.exps("param_data ->> 'meeting_content'", "like", "%" + queryAll + "%");
            SqlExpressionGroup theme = Cnd.exps("param_data ->> 'theme'", "like", "%" + queryAll + "%");
            SqlExpressionGroup createUserName = Cnd.exps(Sqfw_formSummaryForAdminVO::getCreateUserName, "like", "%" + queryAll + "%");
            expressionSql.and(type.or(address).or(meetingContent).or(theme).or(createUserName));
        }
        return cri;
    }

}
